// pages/receive/list/list.js
import api from '../../../utils/api';
import util from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    rlTabList:['暂存','进行中','已拒绝','已通过'],
    searchValue: '',
    activeTab: 0,
    secondTab: 0,
    secondTab1:0,
    tips: '暂无数据？<br/>可能没有订阅单位，点击底部订阅试试吧！',
    listData: [], // 全部到款,我的认领
    // claimedList: [], //我的认领
    currentPage: 1, // 当前页码
    pageSize: 10, // 每页显示数据
    loading: true,
    remind: '下拉加载更多',
    nodata: false, //是否没有数据
    currentDate: new Date().getTime(),
    nowDate: new Date().getTime(),
    searchDate: '', // 月份
    showMonth: false, // 选择月份
    allInfo: {}, // 总结
    showDept: false, // 选择部门
    depts: [], //部门选项
    searchDept: '全部', //部门
    searchGenre: '全部', // 到款类型
    genres: [], //到款类型选项
    showGenre: false, // 选择到款类型
    customDate: '本月', //自定义时间
    custompop: false, // 自定义弹窗
    timeQuantum: [{
      txt: '全部时间',
      checked: false
    }, {
      txt: '本月',
      checked: false
    }, {
      txt: '本周',
      checked: false
    }, {
      txt: '今日',
      checked: false
    }],
    startTime: '', // 全部认领开始时间
    endTime: '', // 全部认领结束时间
    showcalendar: false, // 自定义时间
    maxTime: 0,
    minTime: 0,
    receiveTypeValue:'全部',  //到款类型
    receiveTypes:['全部','银行来款','承兑汇票'],
    showType:false,
    showBusiness:false, //业务类型
    businessTypes:[],
    businessTypeValue:'全部'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  // 选择时间
  showCustom() {
    for(let i=0;i<this.data.timeQuantum.length;i++){
      if(this.data.timeQuantum[i].txt === this.data.customDate){
        this.data.timeQuantum[i].checked = true
      }else{
        this.data.timeQuantum[i].checked = false
      }
    }
    this.setData({
      timeQuantum:this.data.timeQuantum,
      startTime: this.data.startTimeS ? this.data.startTimeS : '',
      endTime: this.data.endTimeS ? this.data.endTimeS : '',
      custompop: true
    })
  },
  // 全部认领 选择时间段
  chooseTimeQuantum(e) {
    let dataset = e.currentTarget.dataset;
    let that = this;
    for (let i = 0; i < that.data.timeQuantum.length; i++) {
      if (that.data.timeQuantum[i].checked) {
        that.data.timeQuantum[i].checked = false
      }
    }
    if (!that.data.timeQuantum[dataset.index].checked) {
      that.data.timeQuantum[dataset.index].checked = true;
      that.customTimeList(dataset.index)
    }
    that.setData({
      timeQuantum: that.data.timeQuantum
    })
  },
  customTimeList(index) {
    let that = this;
    if (index === 0) {
      that.data.startTime = '';
      that.data.endTime = '';
    }
    if (index === 1) {
      let start = new Date().setDate(1)
      let end = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0);
      that.data.startTime = util.formatTime(new Date(start)).split(' ')[0];
      that.data.endTime = util.formatTime(new Date(end)).split(' ')[0];
    }
    if (index === 2) {
      let curr = new Date().getDay()
      let first = util.formatTime(new Date(new Date() - (1000 * 60 * 60 * 24 * (curr - 1)))).split(' ')[0];
      let last = util.formatTime(new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * (7 - curr)))).split(' ')[0];
      that.data.startTime = first;
      that.data.endTime = last;
    }
    if (index === 3) {
      that.data.startTime = util.formatTime(new Date()).split(' ')[0];
      that.data.endTime = that.data.startTime;
    }
    that.setData({
      startTime: that.data.startTime,
      endTime: that.data.endTime
    })
  },
  oncalendarClose() {
    this.setData({
      showcalendar: false
    })
  },
  onshowcalendar() {
    console.log(this.data.startTimeS,this.data.endTimeS)
    let defaultT = [];
    if (this.data.startTime && this.data.endTime) {
      defaultT = [this.data.startTime, this.data.endTime]
    } else {
      defaultT = [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - 1).getTime(), new Date().getTime()]
    }
    this.setData({
      maxTime: new Date().getTime(),
      minTime: new Date(2005, 0, 1).getTime(),
      defaultDate: defaultT,
      showcalendar: true
    })
  },
  oncalendarConfirm(event) {
    let [start, end] = event.detail;
    start = util.formatTime(start).split(' ')[0];
    end = util.formatTime(end).split(' ')[0];
    for (let i = 0; i < this.data.timeQuantum.length; i++) {
      this.data.timeQuantum[i].checked = false
    }
    this.setData({
      startTime: start,
      endTime: end,
      showcalendar: false,
      timeQuantum: this.data.timeQuantum
    })
  },
  oncustomconfirm() {
    this.data.startTimeS = this.data.startTime;
    this.data.endTimeS = this.data.endTime;
    this.data.customDate = this.data.startTimeS.replaceAll('-', '/') + '-' + this.data.endTimeS.replaceAll('-', '/');
    for (let i = 0; i < this.data.timeQuantum.length; i++) {
      if (this.data.timeQuantum[i].checked) {
        this.data.customDate = this.data.timeQuantum[i].txt
      }
    }
    this.setData({
      customDate: this.data.customDate,
      custompop: false,
    })
    this.clearData()
  },

  showTypePicker(){
    this.setData({
      showType:true
    })
  },
  showPicker() {
    this.setData({
      showMonth: true
    })
  },
  showGenreDeptPicker() {
    let that = this;
    that.data.genres = ['全部'];
    api.querySysDictDataAll({
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          res.data.data.forEach(element => {
            that.data.genres.push(element.dictValue)
          });
        }
        that.setData({
          genres: that.data.genres,
          showGenre: true
        })
      }
    })

  },
  showDeptPicker() {
    let that = this;
    that.data.depts = [];
    api.getDeptList({
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          res.data.data.forEach(element => {
            that.data.depts.push(element.deptName)
          });
        }
        that.setData({
          depts: that.data.depts,
          // searchDept:that.data.depts[0],
          showDept: true
        })
      }
    })
  },
  showBusinessTypePicker(){
    let that = this;
    that.data.businessTypes = [];
    api.getDkBusinessType({
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          res.data.data.forEach(item => {
            that.data.businessTypes.push(item.dictValue)
          });
        }
        console.log(that.data.businessTypes)
        that.setData({
          businessTypes: that.data.businessTypes,
          showBusiness: true
        })
      }
    })
  },
  hidePicker() {
    this.setData({
      showMonth: false,
      showGenre: false,
      custompop: false,
      showType:false,
      showBusiness:false
    })
  },
  onHideDept() {
    this.setData({
      showDept: false,
      searchDept:'全部'
    })
    this.clearData()
  },
  // 选择部门
  onDeptChange(event) {
    console.log(event.detail)
    this.setData({
      searchDept: event.detail.value,
      showDept: false
    })
    this.clearData()
  },
  // 全部认领到款类型
  ontypeChange(event){
    this.setData({
      receiveTypeValue:event.detail.value,
      showType:false
    })
    this.clearData()
  },
  // 业务类型
  onbusinessTypeChange(event){
    this.setData({
      businessTypeValue:event.detail.value,
      showBusiness:false
    })
    this.clearData()
  },
  // 选择月份
  onInput(event) {
    this.setData({
      currentDate: event.detail,
      searchDate: event.detail ? this.formatDate(event.detail) : this.data.currentDate,
      showMonth: false
    });
    this.clearData()
  },
  formatDate(date) {
    date = new Date(date);
    let month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
    return `${date.getFullYear()}-${month}`;
  },
  // 到款类型
  onGenreChange(event) {
    this.setData({
      searchGenre: event.detail.value,
      showGenre: false
    })
    this.clearData()
  },
  getData() {
    if (this.data.activeTab == 0) {
      this.getDingyue()
    } else if (this.data.activeTab == 1) {
      this.getAll()
    } else if (this.data.activeTab == 2) {
      this.getClaimed()
    }else if(this.data.activeTab === 3){
      this.getZuifei()
    }
  },
  secondChange1(event) {
    this.setData({
      searchValue: '',
      searchDate: '',
      searchDept: '全部',
      secondTab1: event.detail.index,
    })
    this.clearData()
  },
  getDingyue() {
    let that = this;
    let param = {
      coId: wx.getStorageSync('userInfo').coId,
      searchStr: that.data.searchValue ? that.data.searchValue : '',
      pageNum: that.data.currentPage,
      bankType: that.data.searchGenre,
      pageSize: that.data.pageSize
    };
    api.getUnclaimedListSubs({
      data: param,
      success: function (res) {
        console.log(res.data.data)
        that.analysis(res.data)
      }
    })
  },
  getZuifei(){
    let that = this;
    let param = {
      searchStr: that.data.searchValue ? that.data.searchValue : '',
      pageNum: that.data.currentPage,
      pageSize: that.data.pageSize,
      flowStatus: parseInt(that.data.secondTab1) + 1,
      monthStr: that.data.searchDate,
      deptName: that.data.searchDept==='全部'?'':that.data.searchDept,
    };
    api.getClaimAbolishDataList({
      data: param,
      success: function (res) {
        console.log(res)
        that.analysis(res.data)
      }
    })
  },
  getAll() {
    let that = this;
    let param = {
      coId: wx.getStorageSync('userInfo').coId,
      searchStr: that.data.searchValue ? that.data.searchValue : '',
      pageNum: that.data.currentPage,
      pageSize: that.data.pageSize,
      bankType: that.data.searchGenre,
      monthStr: that.data.searchDate
    };
    api.getUnclaimedList({
      data: param,
      success: function (res) {
        console.log(res.data.data)

        that.analysis(res.data)
      }
    })
  },
  getClaimed() {
    let that = this;
    let claimedType = 1;
    if (that.data.secondTab == 0) {
      claimedType = 1;
    } else if (that.data.secondTab == 1) {
      claimedType = 2;
    } else if (that.data.secondTab == 2) {
      claimedType = 4;
    } else if (that.data.secondTab == 3) {
      claimedType = 3;
    } else if (that.data.secondTab == 4) {
      claimedType = 9;
    } else if (that.data.secondTab == 5) {
      claimedType = 0;
    } else if (that.data.secondTab == 6) {
      claimedType = 5;
    }
    let param = {
      flowStatus: claimedType,
      searchStr: that.data.searchValue ? that.data.searchValue : '',
      pageNum: that.data.currentPage,
      pageSize: that.data.pageSize,
      monthStr: that.data.searchDate,
      deptName: that.data.searchDept==='全部'?'':that.data.searchDept,
      startTime:that.data.startTimeS,
      endTime:that.data.endTimeS,
      receiveType:that.data.receiveTypeValue,
      businessType:that.data.businessTypeValue
    };
    api.getClaimList({
      data: param,
      success: function (res) {
        if (res.data.code == 200) {
          console.log(res.data.data)
          that.analysis(res.data)
        }
      }
    })
  },
  // 清空数据并重新加载数据
  clearData() {
    
    this.setData({
      listData: [],
      currentPage: 1,
      nodata: false,
      loading: true,
      tips: this.data.activeTab == 0 ? '暂无数据？<br/>可能没有订阅单位，点击底部订阅试试吧！' : '暂无数据'
    })
    this.getData()
  },
  // 搜索
  onSearch(event) {
    this.setData({
      searchValue: event.detail.value ? event.detail.value : event.detail,
    })
    this.clearData()
  },
  // 处理数据
  analysis(data) {
    let that = this;
    that.data.allInfo = {};
    if (data.code == 200) {
      if (that.data.activeTab == 1) {
        that.data.allInfo.total = data.data.total
        that.data.allInfo.dkTotalMoney = util.formatFigure(data.data.dkTotalMoney)
        that.data.allInfo.yrlTotalMoney = util.formatFigure(data.data.yrlTotalMoney)
      }
      if (that.data.activeTab == 2) {
        that.data.allInfo.total = data.data.total;
        that.data.allInfo.yrlTotalMoney = util.formatFigure(data.data.yrlTotalMoney)
      }
      that.setData({
        allInfo: that.data.allInfo,
      })
      if (data.data.list.length > 0) {
        console.log(that.data.activeTab)
        if(that.data.activeTab === 3){
          for (let i = 0; i < data.data.list.length; i++) {
            data.data.list[i].code = data.data.list[i].claimAbolishCode
            let now = new Date(data.data.list[i].claimAbolishDate);
            data.data.list[i].date = util.formatTime(now).split(' ')[0];
            data.data.list[i].cusName2 = data.data.list[i].cusName
            data.data.list[i].cusBankAccount = data.data.list[i].cusBankAccount ? (data.data.list[i].cusBankAccount.substring(data.data.list[i].cusBankAccount.length - 4, data.data.list[i].cusBankAccount.length)) : '';
            data.data.list[i].claimMoney = util.formatFigure(data.data.list[i].claimMoney)
            data.data.list[i].money = util.formatFigure(data.data.list[i].receiveMoney)
          }
        }else{
          for (let i = 0; i < data.data.list.length; i++) {
            data.data.list[i].code = that.data.activeTab != 2 ?
              data.data.list[i].code : data.data.list[i].rlCode
            let now = that.data.activeTab != 2 ? new Date(data.data.list[i].receiveDate) : new Date(data.data.list[i].claimDate);
            data.data.list[i].date = util.formatTime(now).split(' ')[0];
            data.data.list[i].cusBankAccount = data.data.list[i].cusBankAccount ? (data.data.list[i].cusBankAccount.substring(data.data.list[i].cusBankAccount.length - 4, data.data.list[i].cusBankAccount.length)) : '';
            data.data.list[i].money = that.data.activeTab != 2 ? util.formatFigure(data.data.list[i].money) : util.formatFigure(data.data.list[i].receiveMoney);
            data.data.list[i].claimMoney = that.data.activeTab == 2 ? util.formatFigure(data.data.list[i].claimMoney) : 0
          }
        }
        that.data.totalPage = data.data.totalPage;
        that.setData({
          listData: that.data.listData.concat(data.data.list),
          loading: false,
          nodata: false,
          remind: data.data.totalPage > data.data.pageNum ? '下拉加载更多' : '已经到底啦～'
        })
      } else {
        that.setData({
          nodata: true
        })
      }

    } else {
      that.setData({
        nodata: true
      })
    }
  },
  onChange(event) {
    this.data.startTime = '';
    this.data.endTime = '';
    if(this.data.activeTab == 2){
      if(event.detail.index===1||event.detail.index===2||event.detail.index===4){
        this.data.startTime = util.formatTime(new Date(new Date().setDate(1))).split(' ')[0];
        this.data.endTime =  util.formatTime(new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))).split(' ')[0];
      }
    }
    this.setData({
      activeTab: event.detail.index,
      secondTab: 0,
      secondTab1:0,
      searchValue: '',
      searchDate: '',
      currentDate: this.data.nowDate,
      searchDept: '全部',
      searchGenre: '全部',
      startTime : this.data.startTime,
      endTime :this.data.endTime,
      customDate:'本月',
      receiveTypeValue:'全部',
      businessTypeValue:'全部'
    })
    this.data.startTimeS = this.data.startTime;
    this.data.endTimeS = this.data.endTime;
    this.clearData()
  },
  secondChange(event) {
    this.data.startTime = '';
    this.data.endTime = '';
    if(this.data.activeTab == 2){
      if(event.detail.index===1||event.detail.index===2||event.detail.index===4){
        this.data.startTime = util.formatTime(new Date(new Date().setDate(1))).split(' ')[0];
        this.data.endTime =  util.formatTime(new Date(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))).split(' ')[0];
      }
    }
    this.setData({
      searchValue: '',
      secondTab: event.detail.index,
      searchDate: '',
      currentDate: this.data.nowDate,
      searchDept: '全部',
      searchGenre: '全部',
      startTime : this.data.startTime,
      endTime :this.data.endTime,
      customDate:'本月',
      receiveTypeValue:'全部',
      allInfo:{}
    })
    this.data.startTimeS = this.data.startTime;
    this.data.endTimeS = this.data.endTime;
    if (this.data.activeTab == 2) {
      this.clearData()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.clearData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.clearData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.totalPage > this.data.currentPage) {
      ++this.data.currentPage;
      this.setData({
        loading: true
      })
      this.getData()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})